<template>
  <Dropdown class="dropdown-add-box" @on-click="selectItem" @on-visible-change="selectChange">
    <input type="text" :value="value" :placeholder="placeholder" class="ivu-input ivu-input-add ivu-input-default" @input="$emit('input', $event.target.value)" @blur="$emit('on-blur', $event.target.value)" >
    <DropdownMenu slot="list">
      <DropdownItem v-for="item in list" v-if="item.name.indexOf(value) !== -1 || !isFilter" :key="item.id" :name="item.name">{{item.name}}</DropdownItem>
      <DropdownItem class="no-data" name="" key=""> 无匹配结果 </DropdownItem>
      <slot name="button">
        <div class="dropdown-add-button">
          <Button type="primary" size="small" @click="$emit('on-add')">{{buttonText}}</Button>
        </div>
      </slot>
    </DropdownMenu>
  </Dropdown>
</template>
<script type="text/javascript">
export default {
  name: 'DropdownAdd',
  data() {
    return {
      isFilter: false
    }
  },
  props: {
    value: {
      type: String
    },
    list: {
      type: Array,
      default: () => {
        return []
      }
    },
    placeholder: {
      type: String,
      default: ''
    },
    buttonText: {
      type: String,
      default: '新增'
    }
  },
  methods: {
    // 选择某项处理， on-blur用于外部错误处理
    selectItem(val) {
      this.$emit('input', val)
      this.$emit('on-blur', val)
    },
    // 选择项显示后才进行过滤，关闭时判断值是否是选择的，如果是手动输入的，清空。
    selectChange(visible) {
      if (visible) {
        this.isFilter = false
      } else {
        for (let i = 0; i < this.list.length; i++) {
          const item = this.list[i]
          if (item.name === this.value) {
            return
          }
        }
        this.$emit('input', '')
      }
    }
  },
  watch: {
    value(val, old) {
      if (val && val !== old) {
        this.isFilter = true
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.dropdown-add-button {
  padding: 8px 10px;
}
.dropdown-add-box {
  width: 100%;
}
.dropdown-add-box /deep/ {
  .ivu-dropdown-item ~ .no-data {
    display: none;
  }
}
</style>
